package com.ruoyi.web.controller.system;

import com.github.pagehelper.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/system/pend")
public class PendingController extends BaseController {
    @Value("${newUrl}")
    private String newUrl;

    private String prefix = "system/check";

    @Autowired
    private IWorkCustomerService workCustomerService;
    @Autowired
    private IWorkFormService workFormService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private IWorkCustomerService iWorkCustomerService;
    @Autowired
    private IWorkFormService iWorkFormService;
    @Autowired
    private IWorkFaultService iWorkFaultService;
    @Autowired
    private IWorkPhotoService iWorkPhotoService;

    //@RequiresPermissions("system:pend:view")
    @GetMapping()
    public String customer() {
        return prefix + "/checkdata";
    }

    //@RequiresPermissions("system:check:view")
    @GetMapping("/finishFrom/{id}")
    public String finishFrom(@PathVariable Long id, ModelMap map) {
        WorkForm workForm = workFormService.selectWorkFormById(id);
        String holdUser = workForm.getHoldUser();
        map.addAttribute("holeName", holdUser);
        map.addAttribute("id", id);
        return prefix + "/checkdd";
    }

    @GetMapping("/finishCheckOk/{id}")
    public String finishCheckOk(@PathVariable Long id) {

        return prefix + "/finishCheck";
    }

    @GetMapping("/newForm/{id}")
    public String newForm(@PathVariable Long id, ModelMap map) {
        map.addAttribute("id", id);
        WorkForm workForm = iWorkFormService.selectWorkFormById(id);
        String holdUser = workForm.getHoldUser();
        map.addAttribute("holdName", holdUser);
        Long userId = ShiroUtils.getUserId();
        map.addAttribute("userId", userId);
        WorkFault workFault = iWorkFaultService.selectWorkFaultByForm(id);
        Long custId = workFault.getCustId();
        String description = workFault.getDescription();
        map.addAttribute("description", description);
        map.addAttribute("custId", custId);
        return prefix + "/newEditFrom";
    }

    @GetMapping("/checkData/{id}")
    public String checkData(@PathVariable Long id, ModelMap model) {
        String loginName = ShiroUtils.getLoginName();
        model.addAttribute("id", id);
        return prefix + "/checkDataAll";
    }

    @GetMapping("/transto/{id}")
    public String transto(@PathVariable Long id, ModelMap model) {
        WorkForm workForm = iWorkFormService.selectWorkFormById(id);

        String username = workForm.getHoldUser();

        List<SysUser> list = iSysUserService.selectUserAll();

        HashMap<Long, String> map = new HashMap<>();
        for (SysUser sysUser : list) {
            if (!sysUser.getLoginName().equals("admin") & !sysUser.getLoginName().equals(username) & sysUser.getDelFlag().equals("0")) {
                map.put(sysUser.getUserId(), sysUser.getLoginName());
            }
        }
        model.addAttribute("user", map);
        model.addAttribute("msg", username);//原持有人
        model.addAttribute("id", id);
        return prefix + "/transTo";
    }

    /**
     * 查询用户列表
     */
    // @RequiresPermissions("system:pend:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkForm workForm) {
        startPage();
        String loginName = ShiroUtils.getLoginName();

        List<FaultCustForm> list = workFormService.selectWorkCheckListOk(workForm, loginName);
        return getDataTable(list);
    }

    @PostMapping("/dataList/{f}")
    @ResponseBody
    public TableDataInfo dataList(WorkForm workForm, @PathVariable("f") Long f) {
        startPage();
        String loginName = ShiroUtils.getLoginName();
        workForm.setId(f);
        List<FaultCustForm> forms = workFormService.selectWorkCheckListOk(workForm, loginName);
        int count = workFormService.selectWorkCheckListByFormId(f);
        bigDataFrom bigDataFrom = new bigDataFrom();
        ArrayList<bigDataFrom> list = new ArrayList<>();
        for (FaultCustForm form : forms) {
            BeanUtils.copyProperties(form, bigDataFrom);
            bigDataFrom.setCount(count + "");
            list.add(bigDataFrom);
        }
        return getDataTable(list);
    }

    /**
     * 新工单申请
     */
    // @RequiresPermissions("system:pend:list")
    @PostMapping("/newCheckForm/{id}")
    @ResponseBody
    public AjaxResult newCheckForm(@PathVariable("id") Long id) {
        return toAjax(workFormService.updateWorkFormByReturnId(id));
    }

    /*
    工单处理完成提交审核
     */
    // @RequiresPermissions("system:pend:list")
    @PostMapping("/finishCheckForm/{id}")
    @ResponseBody
    public AjaxResult finishCheckForm(@PathVariable("id") Long id) {
        return toAjax(workFormService.updateWorkFormBycheckId(id));
    }

    /**
     * 工单转移
     */
    //@RequiresPermissions("system:form:remove")
    @Log(title = "工单表", businessType = BusinessType.check)
    @PostMapping("/transto")
    @ResponseBody
    public AjaxResult transto(int id, int uId) {

        return toAjax(workFormService.updateWorkFormByTransId(id, uId));
    }

    /**
     * 新建工单退回删除
     */
    //@RequiresPermissions("system:form:remove")
    @Log(title = "工单表", businessType = BusinessType.check)
    @PostMapping("/removeForm/{id}")
    @ResponseBody
    public AjaxResult removeForm(@PathVariable("id") Long id) {

        return toAjax(iWorkFormService.deleteWorkFormByFormId(id));
    }

    /**
     * 工单完成处理
     */
    //@RequiresPermissions("system:form:remove")
    @Log(title = "工单表", businessType = BusinessType.check)
    @PostMapping("/finishFrom")
    @ResponseBody
    @Transactional
    public AjaxResult finishFrom(@RequestParam("file") MultipartFile[] file, String description, Long id) {
        Map<String, String> map = new HashMap<>();
        for (MultipartFile multipartFile : file) {
            String fileName = multipartFile.getOriginalFilename();
            int index = fileName.lastIndexOf(".");
            if (index < 0) {
                return toAjax(false);
            }
            String suffixName = fileName.substring(index);
            List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif");
            if (!extList.contains(suffixName)) {
                return toAjax(false);
            }
            fileName = UUID.randomUUID().toString().replace("-", "") + System.currentTimeMillis() + suffixName;
            String url = "localhost:9004" + fileName;
            map.put(fileName, url);
            File dest = new File(newUrl + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                multipartFile.transferTo(dest);
            } catch (IOException e) {
                throw new RuntimeException();
            }
        }
        iWorkFormService.updateWorkFormByWork(id, description);
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            WorkPhoto workPhoto = new WorkPhoto();
            workPhoto.setPhotoUrl(entry.getValue());
            workPhoto.setPhotoName(entry.getKey());
            iWorkPhotoService.insertWorkPhoto(workPhoto);
            iWorkPhotoService.insertWorkPhotobyWorkId(id, workPhoto.getId());
        }
        return toAjax(1);

    }

    //@RequiresPermissions("system:customer:edit")
    @Log(title = "重新编辑", businessType = BusinessType.UPDATE)
    @PostMapping("/editFrom")
    @ResponseBody
    @Transactional
    public AjaxResult addForm(@RequestParam("file") MultipartFile[] file, Long formId, Long userId, String description, Long custId) {
        iWorkFormService.deleteWorkFormByFormId(formId);
        Map<String, String> map = new HashMap<>();
        for (MultipartFile multipartFile : file) {
            String fileName = multipartFile.getOriginalFilename();
            int index = fileName.lastIndexOf(".");
            if (index < 0) {
                return toAjax(false);
            }
            String suffixName = fileName.substring(index);
            List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif");
            if (!extList.contains(suffixName)) {
                return toAjax(false);
            }
            fileName = UUID.randomUUID().toString().replace("-", "") + System.currentTimeMillis() + suffixName;
            String url = "localhost:9004" + fileName;
            map.put(fileName, url);
            File dest = new File(newUrl + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                multipartFile.transferTo(dest);
            } catch (IOException e) {
                throw new RuntimeException();
            }
        }
        WorkForm workForm = new WorkForm();
        workForm.setCreateTime(DateUtils.getNowDate());
        workForm.setCheckStatus("0");
        SysUser sysUser = iSysUserService.selectUserById(userId);
        workForm.setCreateUser(sysUser.getLoginName());
        workForm.setHoldUser(sysUser.getLoginName());
        workForm.setReturnStatus("0");
        workForm.setWorkStatus("0");
        workForm.setTransferStatus("0");

        iWorkFormService.insertWorkForm(workForm);
        WorkFault workFault = new WorkFault();
        workFault.setCustId(custId);
        workFault.setDescription(description);
        workFault.setFormId(workForm.getId());
        iWorkFaultService.insertWorkFault(workFault);
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            WorkPhoto workPhoto = new WorkPhoto();
            workPhoto.setPhotoName(entry.getKey());
            workPhoto.setPhotoUrl(entry.getValue());
            iWorkPhotoService.insertWorkPhoto(workPhoto);
            iWorkPhotoService.insertWorkPhotoByFault(workFault.getId(), workPhoto.getId());
        }

        return toAjax(1);
    }
}
